package com.ruoyi.slope.dataFile.service.impl;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.slope.dataFile.mapper.SlopeDataFileMapper;
import com.ruoyi.slope.dataFile.domain.SlopeDataFile;
import com.ruoyi.slope.dataFile.service.ISlopeDataFileService;

/**
 * 资料管理Service业务层处理
 * 
 * @author psy
 * @date 2025-04-25
 */
@Service
public class SlopeDataFileServiceImpl implements ISlopeDataFileService 
{
    @Autowired
    private SlopeDataFileMapper slopeDataFileMapper;

    /**
     * 查询资料管理
     * 
     * @param id 资料管理主键
     * @return 资料管理
     */
    @Override
    public SlopeDataFile selectSlopeDataFileById(Long id)
    {
        return slopeDataFileMapper.selectSlopeDataFileById(id);
    }

    /**
     * 查询资料管理列表
     * 
     * @param slopeDataFile 资料管理
     * @return 资料管理
     */
    @DataScope(deptAlias = "s")
    @Override
    public List<SlopeDataFile> selectSlopeDataFileList(SlopeDataFile slopeDataFile)
    {
        return slopeDataFileMapper.selectSlopeDataFileList(slopeDataFile);
    }

    /**
     * 新增资料管理
     * 
     * @param slopeDataFile 资料管理
     * @return 结果
     */
    @Override
    public int insertSlopeDataFile(SlopeDataFile slopeDataFile)
    {
        Date time = DateUtils.getNowDate();
        String username = SecurityUtils.getUsername();
        slopeDataFile.setUploader(username);
        slopeDataFile.setUploadTime(time);
        // 前端 fileName: /profile/upload/2025/09/04/xxx.xlsx
        String relativePath = slopeDataFile.getFileName(); // /profile/upload/2025/09/04/xxx.xlsx
        // 去掉前面的 /profile，因为磁盘上没有这个目录
        String filePath = RuoYiConfig.getUploadPath() + relativePath.replaceFirst("/profile/upload", "");
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            // 文件大小
            slopeDataFile.setFileSize(formatFileSize(file.length()));
            // 文件类型（MIME类型）
            try {
                String contentType = Files.probeContentType(Path.of(filePath));
                if (contentType == null) {
                    // fallback 根据后缀
                    String fileName = file.getName();
                    int dotIndex = fileName.lastIndexOf(".");
                    contentType = dotIndex >= 0 ? fileName.substring(dotIndex + 1).toLowerCase() : "unknown";
                }
                slopeDataFile.setFileType(getFriendlyFileType(contentType, file.getName()));
            } catch (Exception e) {
                slopeDataFile.setFileType("unknown");
            }
        } else {
            slopeDataFile.setFileSize("");
            slopeDataFile.setFileType("");
        }
        return slopeDataFileMapper.insertSlopeDataFile(slopeDataFile);
    }

    public static String formatFileSize(long size) {
        if (size <= 0) return "0 B";
        final String[] units = {"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        double humanSize = size / Math.pow(1024, digitGroups);
        return String.format("%.2f %s", humanSize, units[digitGroups]);
    }

    private static String getFriendlyFileType(String mimeType, String fileName) {
        if (mimeType == null || mimeType.isEmpty()) {
            return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        }
        switch (mimeType) {
            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                return "Excel (.xlsx)";
            case "application/vnd.ms-excel":
                return "Excel (.xls)";
            case "application/pdf":
                return "PDF";
            case "image/jpeg":
                return "JPG";
            case "image/png":
                return "PNG";
            case "text/plain":
                return "TXT";
            default:
                return mimeType; // fallback
        }
    }

    /**
     * 修改资料管理
     * 
     * @param slopeDataFile 资料管理
     * @return 结果
     */
    @Override
    public int updateSlopeDataFile(SlopeDataFile slopeDataFile)
    {
        slopeDataFile.setUpdateTime(DateUtils.getNowDate());
        return slopeDataFileMapper.updateSlopeDataFile(slopeDataFile);
    }

    /**
     * 批量删除资料管理
     * 
     * @param ids 需要删除的资料管理主键
     * @return 结果
     */
    @Override
    public int deleteSlopeDataFileByIds(Long[] ids)
    {
        return slopeDataFileMapper.deleteSlopeDataFileByIds(ids);
    }

    /**
     * 删除资料管理信息
     * 
     * @param id 资料管理主键
     * @return 结果
     */
    @Override
    public int deleteSlopeDataFileById(Long id)
    {
        return slopeDataFileMapper.deleteSlopeDataFileById(id);
    }
}
